package zmee.pur.src.opplugin;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.ExtendedDataEntity;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.PreparePropertysEventArgs;
import kd.bos.entity.plugin.args.BeforeOperationArgs;
import kd.scm.common.util.SrmCommonUtil;
import kd.scm.pds.common.extplugin.ExtPluginContext;
import kd.scm.pds.common.extplugin.ExtPluginFactory;
import kd.scm.pds.common.util.PdsCommonUtils;
import kd.scm.src.common.calc.SrcCalcHelper;
import kd.scm.src.common.calc.SrcGlobalCalcContext;

import java.util.Iterator;
import java.util.List;

/**
 * @Author: xw
 * @Date: 2023/02/16/16:27
 * @Description:
 */
public class SrcCompareCalculateOpExt extends AbstractOperationServicePlugIn {
    public SrcCompareCalculateOpExt() {
    }

    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        super.onPreparePropertys(e);
        List<String> fields = e.getFieldKeys();
        fields.add("id");
    }

    @Override
    public void beforeExecuteOperationTransaction(BeforeOperationArgs evt) {
        super.beforeExecuteOperationTransaction(evt);
        String opKey = evt.getOperationKey();
        if ("recalculates".equals(opKey)) {

            List<ExtendedDataEntity> dataEntity = evt.getValidExtDataEntities();
            Iterator var6 = dataEntity.iterator();

            while (var6.hasNext()) {
                ExtendedDataEntity extDataEntity = (ExtendedDataEntity) var6.next();
                DynamicObject billObj = extDataEntity.getDataEntity();
                boolean isUpdateAptitude =
                        "src_aptitudeaudit".equals(billObj.getDataEntityType().getName()) || "src_aptitudeaudit2".equals(billObj.getDataEntityType().getName());
                if (isUpdateAptitude) {
                    this.updateAptitudeResult(billObj);
                }

                SrcGlobalCalcContext context = SrcCalcHelper.syntheticalCalculate("src_compare",
                        PdsCommonUtils.object2Long(billObj.getPkValue()));
                if (!context.isSucced() && !isUpdateAptitude) {
                    evt.setCancel(true);
                    evt.setCancelMessage(context.getMessage().toString());
                }
            }
        }
    }

    private void updateAptitudeResult(DynamicObject billObj) {
        ExtPluginContext context = new ExtPluginContext();
        context.setBillObj(billObj);
        context.setProjectObj(billObj);
        context.setProjectId(SrmCommonUtil.getPkValue(billObj));
        context.setEntityId(billObj.getDataEntityType().getName());
        context.setOperationKey("audit");
        ExtPluginFactory.getInstance();
        ExtPluginFactory.executeExtplugin("SrcAptitudeAuditResultHandler", context, true);
    }
}
